<?php


namespace app\admin\controller;

use app\admin\service\CategoryService;
use app\BaseController;
use think\App;
use think\facade\View;
use think\response\Json;

class Category extends BaseController
{
    protected $service;

    /**
     * Category constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->service = app()->make(CategoryService::class);
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index(): string
    {
        $data['list'] = $this->service->queryList();
        return View::fetch('index', $data);
    }

    public function add(): string
    {
        $data['list'] = $this->service->queryList();
        return View::fetch('add', $data);
    }

    /**
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(): string
    {
        $data['detail'] = $this->service->queryDetail($this->request->get('id'));
        $data['list'] = $this->service->queryList();
        return View::fetch('edit', $data);
    }

    public function save(): Json
    {
        $data['name'] = $this->request->post("name");
        $data['en_name'] = $this->request->post("enName");
        $data['parent_id'] = $this->request->post("parentId");
        $data['description'] = $this->request->post("description");
        $data['is_nav'] = $this->request->post("isNav");
        $data['keywords'] = $this->request->post("keywords");
        $data['sort'] = $this->request->post("sort");
        $data['id'] = $this->request->post("id");
        return success($this->service->save($data));
    }

    public function delete(): Json
    {
        return success($this->service->delete(input("id")));
    }
}